<template>
	<view class="map-picker" @tap="openMap">
		<text v-if="address">{{ address }}</text>
		<text v-else style="color:#999">{{ placeholder }}</text>
	</view>
</template>

<script>
	export default {
		name: 'MapPicker',
		props: {
			placeholder: {
				type: String,
				default: '请选择地图坐标'
			},
			value: {
				type: Object,
				default: () => ({})
			}
		},
		data() {
			return {
				address: '',
				longitude: null,
				latitude: null
			};
		},
		watch: {
			value: {
				handler(newVal) {
					if (newVal && newVal.address) {
						this.address = newVal.address;
						this.longitude = newVal.longitude;
						this.latitude = newVal.latitude;
					}
				},
				immediate: true
			}
		},
		methods: {
			openMap() {
				uni.chooseLocation({
					success: (res) => {
						const data = {
							address: res.address || res.name,
							longitude: res.longitude,
							latitude: res.latitude
						};
						this.address = data.address;
						this.longitude = data.longitude;
						this.latitude = data.latitude;
						this.$emit('input', data); // v-model 支持
						this.$emit('change', data); // 自定义事件
					},
					fail: (err) => {
						console.log('地图选择失败', err);
					}
				});
			}
		}
	};
</script>

<style scoped>
	.map-picker {
		margin-top:20rpx;
		padding: 12px;
		/* border: 1px solid #dcdfe6; */
		border-radius: 4px;
		background-color: #fff;
	}
</style>